package com.spark.gaea.security.backend;

import com.google.common.collect.Maps;
import com.spark.gaea.data.mybatis.Dao;
import com.spark.gaea.security.domain.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Transactional(readOnly = true)
public class MySQLSecurity implements SecurityBackend {
	@Autowired
	private Dao dao;

	@Override
	public String getUserId(final String username) {
		final SecurityUser user = this.dao.get("shiro.query.", "getSecurityUser", username);
		return user.getId();
	}

	@Override
	public SecurityUser getUser(final String username) {
		final SecurityUser user = this.dao.get("shiro.query.", "getSecurityUser", username);
		if (user != null && "01".equals(user.getType())) {
			final Map<String, String> parmas = new HashMap<String, String>();
			parmas.put("type", user.getType());
			parmas.put("id", user.getId());
			Map<String, String> map;
			map = this.dao.get("shiro.query.", "getSecurityUserById", parmas);
			if (map != null && !map.isEmpty() && map.size() > 0) {
				user.setDepartmentId(map.get("departmentId"));
				user.setDepartmentName(map.get("departmentName"));
				user.setDepartmentCode(map.get("departmentCode"));
				user.setPersonId(map.get("personId"));
				user.setPositionId(map.get("positionId"));
				user.setPositionCode(map.get("positionCode"));
				user.setPositionName(map.get("positionName"));
			}
		}
		return user;
	}

	@Override
	public Set<String> getUserRoles(final String userId) {
		final List<String> userRoles = this.dao.getList("shiro.query.", "getSecurityRoles", userId);
		final Set<String> roles = new HashSet<String>();
		roles.addAll(userRoles);
		return roles;
	}

	@Override
	public Set<String> getUserPermissions(final String userId) {
		final List<String> userCmds = this.dao.getList("shiro.query.", "getSecurityPermissions", userId);
		final Set<String> cmds = new HashSet<String>();
		cmds.addAll(userCmds);
		return cmds;
	}

	@Override
	public Set<String> getUserPermissionsByMisid(final String userId, final String misId) {
		final Map<String, String> params = Maps.newHashMap();
		params.put("userId", userId);
		params.put("misId", misId);
		final List<String> userCmds = this.dao.getList("shiro.query.", "getSecurityPermissionsByMisid", params);
		final Set<String> cmds = new HashSet<String>();
		cmds.addAll(userCmds);
		return cmds;
	}
}
